import { Toast, Indicator } from 'mint-ui';
import { fetch, fetchOther,IMAPI } from '../../assets/api/index';
import CosCloud from '../../../static/cos-js-sdk-v4';
import Client from './common';

//获取本地图片
const getLocalPic = (e, results) => {
    if (!e) {
        return;
    }
    let localUrl;
    let reader = new FileReader(),
        getfile = e.srcElement.files[0];
    let fileLimit = 1024 * 1024 * 20;  // 20M图片限制
    if (!getfile.type.includes('image')) {
        Toast("请上传图片格式的文件")
        return false;
    }
    if (getfile.size > fileLimit) {
        Toast('请上传20M以内的图片')
        return false;
    }
    reader.onload = (getfile => {
        return e => {
            results && results(e.srcElement.result);
        };
    })(getfile);
    reader.readAsDataURL(getfile);
};

//图片上传
const changePicFile = (e, fileType) => {
    //fileType文件类型（默认或不传 为普通img图片）head头像 file 文件 audio 音频文件
    let etension = e.target.value.toLowerCase().split('.').splice(-1).toString();
    return new Promise((resolve, reject) => {
        let apiname = "UploadFile/UploadPic";
        if (typeof fileType !== 'undefined') {
            if (fileType == 'audio') {
                apiname = "UploadFile/uploadAudio";
                !etension? etension = "mp3":'';
            } else if (fileType == 'video') {
                apiname = "UploadFile/UploadVideo";
            }
        } else {
            fileType = 'img';
        }
        let queryDom = document.querySelector('#upProgress');
        fetch(apiname, { fileEtension: etension, signType: 0 }).then((res) => {
            let cosdata = res.Result;
            let cos = new CosCloud({
                appid: cosdata.appid, // APPID 必填参数
                bucket: cosdata.bucket, // bucketName 必填参数
                region: cosdata.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
                getAppSign: callback => {
                    callback(cosdata.AppSign);
                },//多次签名 可使用多次
                getAppSignOnce: callback => {
                    callback(cosdata.AppSignOnce);
                }
            });
            uploadFile(e, cosdata, cos, fileType).then(resp => {
                resolve(resp);
            });
        }).catch(err => {
            queryDom.style.display = 'none';
            reject(err);
        });
    });
};

//文件上传
const uploadFile = (e, cosdata, cos, types) => {
    const cosUpload = (bucket, fileName, pics, insertOnly,fileTypes) => {
        return new Promise((resolve, reject) => {
            let successCallBack = result => {
                if (result.code !== 0) {
                    Toast('上传失败');
                    reject(result);
                    return;
                } else {
                    resolve(result.data.source_url);
                    console.log('结果地址:',result.data.source_url);
                }
            };

            let errorCallBack = result => {
                Toast('上传失败,请稍后再试');
                result = result || {};
                reject(result);
                console.log('request error:', result && result.message);
            };

            let percentDom = document.querySelector('#proPercent'),
                inserText;
            let progressCallBack = (curr, sha1) => {
                if(curr){
                    if(fileTypes == 'img1'){
                        inserText = parseInt(curr*50) + '%';
                    }else if(fileTypes == 'img2'){
                        inserText = 50 + parseInt(curr*50) + '%';
                        //console.log('img2222',inserText);
                    }else{
                        inserText = parseInt(curr*100) + '%';
                    }
                    percentDom.innerHTML = inserText;
                }
            };
            let lastTaskId;
            let taskReady = taskId => {
                lastTaskId = taskId;
            };
            cos.uploadFile(successCallBack, errorCallBack, progressCallBack, bucket, fileName, pics, insertOnly, taskReady);
        });
    };
    //let picObjs = [];
    return new Promise((resolve, reject) => {
        let file = e.target.files[0];
        // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传
        //Indicator.open();
        if (types == 'img' || types == 'head') {
            imgReady(file).then(async (resp) => {
              try{
                let picName = cosdata.fileName.split('.');
                let picObjs = [];
                let bigPhoto = await cosUpload(cosdata.bucket,
                    cosdata.fileName, resp.bigPic, 0,'img1');//insertOnly==0 表示允许覆盖文件 1表示不允许
                picObjs.push(bigPhoto);
                let smallPhoto = await cosUpload(cosdata.bucket,
                    picName[0] + 'small.' + picName[1], resp.smallPic, 0,'img2');
                picObjs.push(smallPhoto);
                console.log('最终结果',picObjs);
                //Indicator.close();
                resolve(picObjs);
              }catch(e){
                document.querySelector('#upProgress').style.display = 'none';
                reject(e);
                //Indicator.close();
              }
            });
        } else {
            cosUpload(cosdata.bucket, cosdata.fileName, file, 0).then(resp=>{
                resolve(resp);
                //Indicator.close();
            }).catch(err=>{
                document.querySelector('#upProgress').style.display = 'none';
                reject(err);
                //Indicator.close();
            });
        }
        return false;
    });

};

const imgReady = (obj) => {
    let reader = new FileReader();
    let maxsize = 20 * 1024;
    reader.readAsDataURL(obj);
    return new Promise((resolve, reject) => {
        reader.onload = function (f) {
            let res = this.result;
            let img = new Image();
            if (res.length <= maxsize) {
                resolve(obj);
                return;
            }
            img.onload = async () => {
                let compressedData = await compress(img, obj.type);
                let bigFile = dataURLtoBlob(compressedData.bigPic);
                let smallFile = dataURLtoBlob(compressedData.smallPic);
                resolve({ bigPic: bigFile, smallPic: smallFile });
                img = null;
            };
            img.src = res;
        }
    });
}

const rotateImg = (img, direction, canvas, fileType, compressRate = 600) => {
    let min_step = 0;
    let max_step = 3;
    if (img == null) return;
    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
    let height = img.height;
    let width = img.width;
    //分辨比率压缩
    if (width > compressRate || height > compressRate * 2) {
        let picRate = parseInt(width / compressRate);
        width /= picRate;
        height /= picRate;
    }
    let step = 2;
    if (step == null) {
        step = min_step;
    }
    if (direction == 'right') {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
    }else if(direction == ''){
        step = 0;
    }else if(direction == 'bottomRight'){
        step = 2;
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    let degree = step * 90 * Math.PI / 180;
    let ctx = canvas.getContext('2d');
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height, width, height);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height, width, height);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0, width, height);
            break;
    }
    return canvas.toDataURL(fileType, 0.5);
}

const compress = (img, fileType) => {
    let canvas = document.createElement("canvas");
    let rotateshow, smallshow;
    return new Promise((resolve, reject) => {
        EXIF.getData(img, () => {
            EXIF.getAllTags(img);
            let Orientation = EXIF.getTag(img, 'Orientation');
            switch (Orientation) {
                case 6:
                    rotateshow = rotateImg(img, 'left', canvas, fileType);
                    smallshow = rotateImg(img, 'left', canvas, fileType, 300);
                    break;
                case 8:
                    rotateshow = rotateImg(img, 'right', canvas, fileType);
                    smallshow = rotateImg(img, 'right', canvas, fileType, 300);
                    break;
                case 3:
                    rotateImg(img, 'bottomRight', canvas, fileType);
                    rotateshow = rotateImg(img, 'bottomRight', canvas, fileType);
                    smallshow = rotateImg(img, 'bottomRight', canvas, fileType, 300);
                    break;
                default:
                    rotateshow = rotateImg(img, '', canvas, fileType);//img.src;
                    smallshow = rotateImg(img, '', canvas, fileType, 300);
            }
            resolve({ bigPic: rotateshow, smallPic: smallshow });
        });
    });
}

const dataURLtoBlob = dataurl => {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

//关注或取消关注
//1关注 3取消关注
const changeFocus = (loginInfo, toId, type = 3) => {
    let focusURL = IMAPI;
    if (type == 3) {
        focusURL += "TerminalUserAttention/AddAttention";
    } else {
        focusURL += "TerminalUserAttention/CancelAttention";
    };
    return fetchOther(focusURL, {
        ...loginInfo,
        ToIdentifier: toId
    });
}
const Chat = {
    getLocalPic,
    changePicFile,
    changeFocus
}
export default Chat